package org.spiderdesign.interceptor;

import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Value("${spider.login.url}")
    private String defaultUrl;

    @Override
    public boolean preHandle(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession(false);
        if(session != null && session.getAttribute("user_token") != null) {
            //用户已登录，通过校验
            return true;
        }
        //检验url是否正确
        if(!(defaultUrl.startsWith("/"))){
            defaultUrl = "/" + defaultUrl;
        }
        //校验不通过，跳转到登录界面
        response.sendRedirect(defaultUrl);
        return false;
    }




}
